//
//  DateExtension.swift
//  Pods
//
//  Created by 张文晏 Yokoyama on 2018/10/14.
//
//

import UIKit

public extension Date {
    public func string(withFormat format: String = "yyyy/MM/dd") -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
    
    public func formated(withFormat format: String = "yyyy/MM/dd") -> Date {
        let formatter: DateFormatter = .init()
        formatter.dateFormat = format
        let dateString = formatter.string(from: self)
        return formatter.date(from: dateString)!
    }
    
    public func daysSince(_ anotherDate: Date) -> Int {
        let fromDate = dateFromComponents(self)
        let toDate = dateFromComponents(anotherDate)
        let components = Calendar.current.dateComponents([.day], from: fromDate, to: toDate)
        return components.day!
    }
    
    private func dateFromComponents(_ date: Date) -> Date {
        let calender   = Calendar.current
        let components = calender.dateComponents([.year, .month, .day], from: date)
        return calender.date(from: components)!
    }
}
